import { CacheService } from '@app/cache';
import { ConfigureService } from '@app/configure';
import { OfficialUser } from '@app/db/entity/OfficialUser';
import { Injectable } from '@nestjs/common';
import { DataSource, FindOptionsWhere, Like } from 'typeorm';
import { DbService } from '../../db/db.service';
import PageDto from './dto/page.dto';
import { ImclientService } from '@app/imclient';

@Injectable()
export class OfficialUserService {
    constructor(
        private readonly db:DbService,
        private readonly config:ConfigureService,
        private readonly cache:CacheService,
        private readonly dataSource: DataSource,
        private readonly imclient:ImclientService,
    ){}


    async page(dto:PageDto) {
        let result:PaginationResult<OfficialUser> = {
            total : 0,
            rows : []
        }

        let where:FindOptionsWhere<OfficialUser> = {
            
        }



        result.total = await this.db.officialUser.count(where)

        if(result.total > 0) {
            result.rows = await this.db.officialUser.pagination(dto.pageNo, dto.pageSize, where, null, {id : 'DESC'})
        }

        return result
    }

    async add(dto:OfficialUser) {
        const imUserId = dto.imUserId
        const info = {
            avatar: this.config.get('upload.staticURL') + dto.avatar,
            name: dto.name,
        }

        const queryRunner = this.dataSource.createQueryRunner();

        await queryRunner.connect();
        await queryRunner.startTransaction();
        try {
            const r = await queryRunner.manager.insert(OfficialUser, {...dto})
        
            const r2 = await this.imclient.createUser(imUserId, info)

            if(r2 == null || r2.code != 200) {
                await queryRunner.rollbackTransaction();
                return false
            }

            await queryRunner.commitTransaction();

            return true
        } catch (err) {
            await queryRunner.rollbackTransaction();
        } finally { 
            await queryRunner.release();
        }

        return false
    }
}
